package com.lwf.thymeleafdemo1.exception.aspect;


import com.lwf.thymeleafdemo1.exception.entiry.Result;
import com.lwf.thymeleafdemo1.exception.utils.ExceptionHandle;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author liwenfeng
 * @Description dongruan
 * @Date 2023/08/11/9:44
 * @Version 1.0
 */
@Aspect
@Component
public class HttpAspect {

    private final static Logger LOGGER = LoggerFactory.getLogger(HttpAspect.class);

    @Autowired
    private ExceptionHandle exceptionHandle;
    // @Pointcut用法详解：https://www.cnblogs.com/Timeouting-Study/p/15179264.html
    // 下面解释为com.lwf.exception.controller里所有public方法
    // @Pointcut("execution(public * com.lwf.exception.controller.*.*(..))")  //作用于包下
    @Pointcut("execution(public * com.lwf.thymeleafdemo1.exception.controller.ResultController.*(..))") //作用于类中
    public void log(){

    }
    // @Before是在所拦截方法执行之前执行一段逻辑。
    // @After 是在所拦截方法执行之后执行一段逻辑。
    // @Around是可以同时在所拦截方法的前后执行一段逻辑。
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //url
        LOGGER.info("url={}",request.getRequestURL());
        //method
        LOGGER.info("method={}",request.getMethod());
        //ip
        LOGGER.info("id={}",request.getRemoteAddr());
        //class_method
        LOGGER.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName() + "," + joinPoint.getSignature().getName());
        //args[]
        LOGGER.info("args={}",joinPoint.getArgs());
    }

    @Around("log()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Result result = null;
        try {

        } catch (Exception e) {
            return exceptionHandle.exceptionGet(e);
        }
        if(result == null){
            return proceedingJoinPoint.proceed();
        }else {
            return result;
        }
    }

    @AfterReturning(pointcut = "log()",returning = "object")//打印输出结果
    public void doAfterReturing(Object object){
        LOGGER.info("response={}",object.toString());
    }
}

